<?php

namespace common\models\datas;

use frontend\models\datas\AccountRecord;
use frontend\models\datas\Orders;
use Yii;
use common\components\helpers\Fun;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use frontend\models\datas\Sales;
use common\models\datas\Student;
use common\components\extenders\MenuManage;
use yii\web\IdentityInterface;
use zhtfrontend\models\datas\CustomerRelationship;

/**
 * This is the model class for table "{{%customer}}".
 *
 * @property integer $id
 * @property integer $site_id
 * @property string $name
 * @property string $sex
 * @property integer $age
 * @property string $logo
 * @property string $mobile
 * @property string $password
 * @property string $account
 * @property integer $integral
 * @property integer $created_at
 * @property integer $card_id
 */
class Customer extends \common\components\bases\BaseModel implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    //use TelecaptchaTrait;
    public $password_r;
    public $pay_password;
    public $confirm_pay_password;

    //remove qrcode by xiaofeng| 20151224public $check_book;//0：没有微信;1：有微信

    public static function tableName()
    {
        return '{{%customer}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'mobile','sex','age'], 'required', 'on' => ['create', 'update']],
            [['site_id', 'age', 'integral', 'created_at', 'source','grade_id','mechanic_id'], 'integer'],//remove qrcode by xiaofeng| 20151224, 'check_book'
            [['mobile','email'],'trim'],
            ['mobile', 'match', 'pattern' => '/^1([0-9]{9})/', 'message' => '手机号码格式错误'],
            //手机号直接唯一得了，跟site_id没啥关系了['mobile','check_unique'],
            ['mobile','unique','on' => ['create']],
            ['email', 'email', 'message' => '邮箱格式错误'],
            /**remove qrcode by xiaofeng[['qrcode'],'required','when'=>function($model){
             * return $model->check_book == 1;
             * }],*/
            [['recommended_times','by_recommended'], 'number'],
            [['nick_name'], 'string', 'max' => 200],
            [['name'], 'string', 'max' => 60],
            [['logo', 'wechat','gttopenid','zhtopenid','gxyopenid','remarks'], 'string', 'max' => 255],//remove qrcode by xiaofeng, 'qrcode'
            [['mobile', 'card_id'], 'string', 'max' => 20],
            [['province', 'city','region','card_qrcode'], 'string', 'max' => 100],
            [['card_id'], 'required', 'on' => ['card','bindcard']],
            [['card_id'], 'card_check','on' => ['card','bindcard']],
            [['password'], 'string', 'max' => 60, 'min' => 6, 'on' => ['create','change']],
            [['pay_password'], 'string','max' => 60, 'min' => 6, 'on' => ['card']],
            [['pay_password'], 'set_pay_password', 'skipOnEmpty'=>false, 'on' => ['card']],
            [['confirm_pay_password'], 'validate_confirm_pay_password', 'skipOnEmpty'=>false, 'on' => ['card']],
            [['mobile'], 'string', 'max' => 11, 'min' => 11],
           // [ 'password', 'required', 'message' => '请输入密码', 'on' => ['create','change']],
          //  ['password_r', 'required', 'message' => '请输入确认密码', 'on' => ['create','change']],
           // [['password_r'], 'password_check', 'on' => ['create']],
            [['sex'], 'string'],
            ['name', 'string', 'min' => 2, 'max' => 15,'on' => ['create', 'update','change']],

            ['age', 'compare', 'compareValue' => 0, 'operator' => '>='],
            ['age', 'check_age','on'=>['create']],

//            [['name'], 'name_check'],
//            [['account'],'actual_back_check','on'=>['cash_back']]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', '编号'),
            'site_id' => Yii::t('common', '分店编号'),
            'card_id' => Yii::t('common', '卡号'),
            'name' => Yii::t('common', '姓名'),
            'sex' => Yii::t('common', '性别'),
            'age' => Yii::t('common', '出生年份'),
            'logo' => Yii::t('common', '头像'),
            'mobile' => Yii::t('common', '手机号码'),
            'password' => Yii::t('common', '密码'),
            'password_r' => Yii::t('common', '确认密码'),
            /*#147 字段存放到新表中了'account' => Yii::t('common', '账户'),*/
            'integral' => Yii::t('common', '积分'),
            'wechat' => Yii::t('common', '关联微信号'),
            'created_at' => Yii::t('common', '加入时间'),
            'is_sender' => Yii::t('common', '能否发卡'),//0否|1是
            /*remove qrcode by xiaofeng'qrcode' => Yii::t('common', '二维码'),*/
            'email' => Yii::t('common', '邮箱'),
            'nick_name' => Yii::t('common', '昵称'),
            'source' => Yii::t('common', '来源'),
            'grade_id' => Yii::t('common', '会员等级'),
            /*#147 字段存放到新表中了'scholarship_available' => Yii::t('common', '可用奖学金'),
            'scholarship_frozen' => Yii::t('common', '不可用奖学金'),*/
            'is_validate' => Yii::t('common', '是否验证'),
            /*#147 字段存放到新表中了'deposit' => Yii::t('common', '保证金'),*/
            'pay_password' => Yii::t('common', '支付密码'),
            'recommended_times' => Yii::t('common','推荐次数'),
            'by_recommended' => Yii::t('common','被推荐人id'),
            'province' => Yii::t('common','省份'),
            'city' => Yii::t('common','城市'),
            'region' => Yii::t('common','地区'),
            'card_qrcode' => Yii::t('common','二维码内容'),
            'gttopenid' => Yii::t('common','共同体的openid'),
            'zhtopenid' => Yii::t('common','综合体的openid'),
            'gxyopenid' => Yii::t('common','管弦乐的openid'),
            'confirm_pay_password' => Yii::t('common','确认支付密码'),
            /*remove qrcode by xiaofeng'check_book' => Yii::t('common', '是否有微信账号'),*/
            //'telecaptcha' => \Yii::t('common', '验证码'),
            'remarks' => Yii::t('common','备注'),
            'mechanic_id' => Yii::t('common','机构id'),
            'is_old' => Yii::t('common','是否是老生'),
        ];
    }

    public function extraFields()
    {
        return [
            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    ['delete' => function ($data) {
                        $orders = [];
                        $site_cache  = Fun::cache('site_cache',false);
                        if($site_cache != null) {
                            foreach($site_cache as $key=>$site) {
                                if (isset($site['db'])) {
                                    $orders = (new \yii\db\Query())
                                        ->select('*')
                                        ->from('{{%orders}}')
                                        ->where(['customer_id' => $data['id']])
                                        ->all(\Yii::createObject($site['db']));
                                    if (!empty($orders))
                                        break;
                                }
                            }
                        }
                        $dues = CustomerDues::find()->where(['customer_id'=>$data['id']])->one();
                        $log = DepositLog::find()->where(['customer_id'=>$data['id']])->one();
                        if (!empty($orders) || $dues!=null || $log!=null) {
                            return '<button class="yx-btn-disabled" type="button">删除</button>';
                        } else {
                            if(isset(\Yii::$app->user->identity->role) && \Yii::$app->user->identity->role == 'admin'){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" type="button">删除</button>';
                            }

                        }
                    },
                        'update' => function ($data) {
                            if(isset(\Yii::$app->user->identity->role) && \Yii::$app->user->identity->role == 'admin'){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" type="button">修改</button>';
                            }
                        },
                        'details'=>function(){
                            return '';
                        }
                    ]
                )->create();
            },
            'student_name' => function () {
                return (!empty($this->student->name)) ? $this->student->name : '';
            },
            'grade' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    $customergrade = Customergrade::findOne(['id'=>$cba->grade_id]);
                    return $customergrade->name;
                }else{
                    return '普通会员';
                }
                /*if($this->customergrade != null && $this->customergrade->name != null){
                    return $this->customergrade->name;
                }else{return '普通会员';}*/
            },
            'grade_id' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    $customergrade = Customergrade::findOne(['id'=>$cba->grade_id]);
                    return $customergrade->id;
                }else{
                    return 1;
                }
            },
            'account' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    return $cba['cash']?$cba['cash']:0;
                }else{
                    return 0;
                }
            },
            'scholarship_available' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    return $cba['scholarship_available']?$cba['scholarship_available']:0;
                }else{
                    return 0;
                }
            },
            'scholarship_frozen' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    return $cba['scholarship_frozen']?$cba['scholarship_frozen']:0;
                }else{
                    return 0;
                }
            },
            'deposit' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    return $cba['deposit']?$cba['deposit']:0;
                }else{
                    return 0;
                }
            }

        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['is_sender'] = function () {
            switch ($this->is_sender) {
                case 0:
                    return \Yii::t('frontend', '否');
                case 1:
                    return \Yii::t('frontend', '是');
            }
        };
        $fields['sex'] = function () {
            switch ($this->sex) {
                case 'Male':
                    return \Yii::t('frontend', '男');
                case 'Female':
                    return \Yii::t('frontend', '女');
            }
        };
        $fields['wechat'] = function () {
            if ($this->wechat == null) {
                return \Yii::t('frontend', '暂无');
            } else return $this->wechat;
        };
        $fields['age'] =function(){
            if($this->age > 0){
                return (int)date('Y')-$this->age;
            }else{
                return 0;
            }
        };

        return $fields;
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],

                ],
            ],

        ]);
    }

    //字段关联
    public function getAccountRecord()
    {
        return $this->hasOne(AccountRecord::className(), ['customer_id' => 'id']);
    }

    public function getCustomerBranchaccount(){
        $site_id = Fun::getSiteId();
        $cba = CustomerBranchaccount::findOne(['customer_id'=>$this->id,'site_id'=>$site_id]);
        return $cba;
    }

    public function getGrade(){
        return $this->hasOne(Customergrade::className(),['id'=>'grade_id']);
    }

    public function getIntegralRecord()
    {
        return $this->hasOne(IntegralRecord::className(), ['customer_id' => 'id']);
    }

    //更新后分别向关联表中插入数据
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if($insert){
            $mobile=$this->mobile;
            $customer_relationship=CustomerRelationship::find()->where(['mobile'=>$mobile,'site_id'=>$this->site_id])->one();
            if(!isset($customer_relationship)){
                $customer_relationship_model=new CustomerRelationship();
                $customer_relationship_model->name=$this->name;
                $customer_relationship_model->sex=$this->sex;
                $customer_relationship_model->mobile=$this->mobile;
                $customer_relationship_model->status=2;
                $customer_relationship_model->created_at=time();
                $customer_relationship_model->customer_id=$this->id;
                $customer_relationship_model->save(false);
            }
        }
//        if($insert){
//            Fun::getSiteDatabases($this->site_id)->createCommand()->insert('{{%account_record}}', [
//                'customer_id' => $this->id,
//                'site_id' => Fun::getSiteId(),
//                'cash' => $this->account,
//                'user_id' => 1,
//                'created_at' => $this->created_at
//            ])->execute();
//            Fun::getSiteDatabases($this->site_id)->createCommand()->insert('{{%integral_record}}', [
//                'customer_id' => $this->id,
//                'site_id' => Fun::getSiteId(),
//                'integral' => $this->integral,
//                'user_id' => 1,
//                'created_at' => $this->created_at
//            ])->execute();
//            \Yii::$app->db->createCommand()->insert('{{%customer_site}}', [
//                'customer_id' => $this->id,
//                'site_id' => $this->site_id,
//            ])->execute();
//        }

    }

    public function afterDelete(){
        parent::afterDelete();
        $student = Student::find()->where(['customer_id'=>$this->id])->one();
        if($student !== null){
            $student->delete();
        }
    }
    public function actual_back_check($attribute)
    {

        $money = ($this->accountRecord->pay_cash) + ($this->accountRecord->pay_pos);
        if ($this->account < $money) {
            $this->addError($attribute, Yii::t('frontend', '实际退款金额不得大于账户剩余金额'));
        }
    }
    public function check_age($attribute){
        if(strlen($this->$attribute)>4 || strlen($this->$attribute)<4){
            $this->addError($attribute, Yii::t('common', '请输入正确的年份'));
        }

    }

    public function password_check($attribute)
    {
        if ($this->password !== $this->$attribute) {
            $this->addError($attribute, Yii::t('common', '确认密码必须与新密码相同'));
        }
    }
    public function set_pay_password($attribute)
    {
        $account = CustomerBranchaccount::find()->where(['customer_id'=>$this->id,'site_id'=>Fun::getSiteId()])->one();
        if(($account->pay_password == null || $account->pay_password == '') && $this->$attribute == ''){
            $this->addError($attribute, Yii::t('common', '请设置支付密码'));
        }
    }
    public function validate_confirm_pay_password($attribute)
    {
        if($this->pay_password != null || $this->pay_password != ''){
            if($this->pay_password != $this->$attribute)
            $this->addError($attribute, Yii::t('common', '两次密码不一致！'));
        }
    }

    public function card_check($attribute)
    {
        if($attribute != null) {
            $data = Customer::find()->where(['card_id' => $this->$attribute])->andWhere("id!=$this->id")->one();
            if ($data != null || strlen($this->$attribute) != 10) {
                $this->addError($attribute, Yii::t('common', '此卡号已存在或卡号错误'));
            }
        }
    }

    /*public function check_unique($attribute){
        $site_id = Fun::getSiteId();
        $exist_customer = Customer::find()->where(['mobile' => $this->$attribute,'site_id'=>$site_id])->one();
        if(!empty($exist_customer)){
            $this->addError($attribute, Yii::t('frontend', '手机号已被占用'));
        }
    }*/
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    public function getStudent()
    {
        return $this->hasOne(Student::className(), ['customer_id' => 'id']);
    }

    public function getCustomergrade(){
        return $this->hasOne(Customergrade::className(),['id'=>'grade_id']);
    }


    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id]);
    }

    public static function findByUsername($name)
    {
        return static::findOne(['name' => $name]);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function getAuthKey()
    {
        // TODO: Implement getAuthKey() method.
    }

    public function validateAuthKey($authKey)
    {
        // TODO: Implement validateAuthKey() method.
    }


}
